import axios from 'axios'
import { requestConfig, getApiUrl } from '@/config/api'
import { ElMessage } from 'element-plus'

// 创建axios实例
const service = axios.create(requestConfig)

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    // 可以在这里添加token等
    // config.headers['Authorization'] = 'Bearer ' + getToken()
    return config
  },
  error => {
    console.log('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 这里根据后端返回的数据结构进行调整
    if (res.code && res.code !== 200) {
      ElMessage.error(res.message || 'Error')
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('Response Error:', error)
    ElMessage.error(error.message || 'Request Error')
    return Promise.reject(error)
  }
)

// 通用请求方法
export const request = {
  get(url, params = {}) {
    return service.get(getApiUrl(url), { params })
  },
  
  post(url, data = {}) {
    return service.post(getApiUrl(url), data)
  },
  
  put(url, data = {}) {
    return service.put(getApiUrl(url), data)
  },
  
  delete(url, params = {}) {
    return service.delete(getApiUrl(url), { params })
  }
}

export default service